<template>
  <div class="app-container">
    <div class="designer" style="height: 100%">
      <!-- 顶部搜索和操作按钮 -->
      <div style="marginBottom: 20px">
        <el-input
          v-model="searchText"
          placeholder="请输入要查询的关键字"
          size="small"
          style="width: 200px"
        ></el-input>
        <el-button style="marginLeft: 10px" icon="el-icon-search" type="primary" size="small"  @click="searchChange">搜索</el-button>
        <el-button style="marginLeft: 10px" icon="el-icon-refresh"  size="small" @click="resetSearch">重置</el-button>
        <div style="float: right">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="operate({},'新增')">新增</el-button>
          <!-- <el-button size="small" icon="el-icon-delete" @click="multiDelPortal" :disabled="multipleSelection.length === 0">批量删除</el-button> -->
          <el-tooltip class="item" effect="dark" content="显隐" placement="top">
            <el-button icon="el-icon-s-operation" circle @click="drawer = true" ></el-button>
          </el-tooltip>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        stripe
        style="width: 100%; marginBottom: 20px"
        size="small"
        @selection-change="handleSelectionChange"
        v-loading="tableLoading"
        class="tableInfo"
        :row-key="getRowKeys"
        row-key="id"
      >
        <!-- <el-table-column
          type="selection"
          width="80"
          align="center"
          :reserve-selection="true"
        ></el-table-column> -->
        <el-table-column
          label="序号"
          width="80"
          align="center"
          v-if="!showHideData[0].hide"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{scope.$index + (page.pageNo - 1) * page.pageSize + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="databaseName"
          label="连接名称"
          sortable
          align="center"
          v-if="!showHideData[1].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="alias"
          label="别名"
          sortable
          align="center"
          v-if="!showHideData[2].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="type"
          label="类型"
          sortable
          align="center"
          v-if="!showHideData[3].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="ip"
          label="数据库IP"
          sortable
          align="center"
          v-if="!showHideData[4].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="port"
          label="数据库端口"
          sortable
          align="center"
          v-if="!showHideData[5].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="username"
          label="数据库账号"
          sortable
          align="center"
          v-if="!showHideData[6].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="description"
          label="描述"
          sortable
          align="center"
          v-if="!showHideData[7].hide"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="operate(scope.row,'查看')">查看</el-button>
            <el-button size="small" type="text" @click="operate(scope.row,'编辑')">编辑</el-button>
            <el-button size="small" type="text" style="color: red" @click="delList(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :layout="layout"
        :total="pageTotal"
        :page-size="page.pageSize"
        :page-sizes="pageSizes"
        :current-page="page.pageNo"
        style="float: right"
        @size-change="sizeChange"
        @current-change="currentChange"
      >
      </el-pagination>
      <el-dialog
        :title="status === 'add' ? '添加数据库' : '编辑数据库'"
        :visible.sync="showDialog"
        @close='cancelFields'
      >
        <el-form :model="form" ref="basicForm" label-width="120px">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item
                label="库类型:"
                prop="type"
                :rules="[
                  {
                    required: true,
                    message: '请选择库类型',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-select v-model="form.type" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item
                label="数据库IP:"
                prop="ip"
                :rules="[
                  {
                    required: true,
                    message: '请填写数据库ip',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model="form.ip"
                  placeholder="请填写数据库ip"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="数据库端口:"
                prop="port"
                :rules="[
                  {
                    required: true,
                    message: '请填写数据库端口',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model="form.port"
                  placeholder="请填写数据库端口"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item
                label="数据库账号:"
                prop="username"
                :rules="[
                  {
                    required: true,
                    message: '请填写数据库账号',
                    trigger: 'blur',
                  },
                ]"
                class="formnum"
              >
                <el-input
                  v-model="form.username"
                  placeholder="请填写数据库账号"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="数据库密码:"
                prop="password"
                :rules="[
                  {
                    required: true,
                    message: '请填写数据库密码',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  type="password"
                  v-model="form.password"
                  placeholder="请填写数据库密码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" >
            <el-col :span="20">
              
              <el-form-item
                prop="databaseName"
                :rules="[
                  {
                    required: true,
                    message: '请填写连接名称',
                    trigger: 'blur',
                  },
                ]"
              >
              <span slot="label">
                连接名称
                <el-tooltip content="Mysql为数据库名称，DM为自定义名称" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
                <el-input
                  v-model="form.databaseName"
                  placeholder="请填写连接名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="testConnect">测试连接</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item
                label="别名:"
                prop="alias"
                :rules="[
                  {
                    required: true,
                    message: '请填写别名',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model="form.alias"
                  placeholder="请填写别名"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item
                label="描述:"
                prop="description"
              >
                <el-input
                  type="textarea"
                  v-model="form.description"
                  :rows="5" 
                  maxlength="200" 
                  show-word-limit
                  placeholder="请填写描述"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelFields">取 消</el-button>
          <el-button type="primary" @click="submit()" :disabled="updateFlag">确 定</el-button >
        </div>
      </el-dialog>
      <el-dialog
        title="查看"
        :visible.sync="viewDialog"
      >

        <el-descriptions :column="2" :colon="false">
          <el-descriptions-item label="连接名称：" labelClassName="databaseName">{{this.form.databaseName}}</el-descriptions-item>
          <el-descriptions-item label="别名：">{{this.form.alias}}</el-descriptions-item>
          <el-descriptions-item label="类型：">{{this.form.type}}</el-descriptions-item>
          <el-descriptions-item label="数据库IP：">{{this.form.ip}}</el-descriptions-item>
          <el-descriptions-item label="数据库端口：">{{this.form.port}}</el-descriptions-item>
          <el-descriptions-item label="数据库账号：">{{this.form.username}}</el-descriptions-item>
          <el-descriptions-item label="描述：" labelStyle='{color:red}' span="1">{{this.form.description}}</el-descriptions-item>
          <el-descriptions-item ></el-descriptions-item>
        </el-descriptions>
      </el-dialog>
      <!-- 列显隐 -->
      <el-drawer :visible.sync="drawer" direction="rtl">
        <span slot="title" style="fontSize:18px;font-weight:500;color: #262626;">列显隐</span>
        <el-table
          :data="showHideData"
          size="small"
          border
          style="width: 80%; marginLeft: 10%"
        >
          <el-table-column prop="columnName" label="列名" align="center">
          </el-table-column>
          <el-table-column prop="hide" label="隐藏" align="center">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.hide"></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
    </div>
  </div>
</template>
<script>
import {createDatabase,testDatabase,updateDatabase,getPageDatabase,getBack,deleteList} from "@/api/infra/dbDoc";
import { encryption} from "@/utils/auth";
export default {
  components: {},
  data() {
    return {
      passwordFlag: '',
      // testPassWord: '',
      updateFlag:false,
      status: "add", //判断是新增还是编辑
      options: [
        {
          value: "SqlServer",
          label: "SqlServer",
        },
        {
          value: "Oracle",
          label: "Oracle",
        },
        {
          value: "MySql",
          label: "MySql",
        },
        {
          value: "Postgresql",
          label: "Postgresql",
        },
         {
          value: "DM",
          label: "DM",
        },
      ], //库类型选项
      form: {
        id:'',
        type: "",
        ip:'',
        port:'',
        username:'',
        password:'',
        databaseName:'',
        alias:'',
        description:''
      },
      //列显隐
      showHideData: [
        {
          columnName: "序号",
          hide: false,
        },
        {
          columnName: "连接名称",
          hide: false,
        },
        {
          columnName: "别名",
          hide: false,
        },
        {
          columnName: "类型",
          hide: false,
        },
        {
          columnName: "数据库IP",
          hide: false,
        },
        {
          columnName: "数据库端口",
          hide: false,
        },
         {
          columnName: "数据库账号",
          hide: false,
        },
        {
          columnName: "描述",
          hide: false,
        },
      ],
      drawer: false, //列显隐抽屉
      showDialog: false, //显示新增/编辑界面
      viewDialog:false,//显示查看界面
      tableLoading: false, //表格加载
      searchText: "", //关键字搜索
      layout: "prev, pager, next,sizes,jumper", //分页显示布局
      pageSizes: [10, 20, 30, 50], //分页显示每页条数选择
      pageTotal: 3, //数据总条数
      page: {
        pageNo: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      superior: [], //上级功能
      tableData:[], //数据列表
      // tableData: [
      //   {
      //     databaseName: "名称一",
      //     alias: "名称一别名asssssdadaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      //     type: "type1aaaaaaaaaaaaaa",
      //     ip: "ip1aaaaaaaaaaaaaa",
      //     port: "port1aaaaaaa",
      //     username:'username',
      //     description: "描述1",
      //   },
      //   {
      //     databaseName: "名称二",
      //     alias: "名称一别名assaaaaaa",
      //     type: "type1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      //     ip: "ip1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      //     port: "port1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      //     username:'username',
      //     description: "描述2",
      //   },
      //   {
      //     databaseName: "名称三",
      //     alias: "名称一别名asssssdadaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      //     type: "type1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      //     ip: "ip1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      //     port: "port1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      //     username:'username',
      //     description: "描述3",
      //   },
      // ],
      multipleSelection: [], //多选
    };
  },
  mounted() {
    // 阻止默认行为
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
    this.getList(); //获取列表数据
    // this.tableLoading = true
  },
  watch: {},
  methods: {
    //测试连接
    testConnect(){
       let params = {}
      if(this.status == 'add'){
        params = {
          type: this.form.type,
          ip: this.form.ip,
          port: this.form.port,
          username:this.form.username,
          password: encryption(this.form.password),
          databaseName: this.form.databaseName,
        }
      }else{
        let pass = this.passwordFlag
        let newpass = this.form.password
        params = {
          type: this.form.type,
          ip: this.form.ip,
          port: this.form.port,
          username:this.form.username,
          password: pass ===newpass ?  this.form.password: encryption(this.form.password),
          databaseName: this.form.databaseName,
        }
      }
      
      //数据库创建
      testDatabase(params).then((res) => {
        if (res.code === 0) {
          this.$message.success('测试连接成功')
        }
      })
      .catch((e) => console.log(e));
    },
    //多选rowkey
    getRowKeys(row) {
      return row.id;
    },
    //获取列表数据
    getList() {
      // alert(1)
      this.tableLoading = false;
      // let params = {
      //   ...this.page, //页配置
      //   portalName: this.searchText, //名称关键字
      // };
      // getPagePortal(params)
      //   .then((res) => {
      //     if (res.code === 0) {
      //       this.tableData = res.data.list;
      //       this.pageTotal = res.data.total;
      //       this.tableLoading = false;
      //     }
      //   })
      //   .catch((e) => {
      //     this.tableLoading = false;
      //   });
    },

    getList() {
      this.tableLoading = false;
      let params = {
        ...this.page, //页配置
        keyword: this.searchText, //名称关键字
      };
      getPageDatabase(params).then((res) => {
        if (res.code === 0) {
          this.tableData = res.data.list;
          this.pageTotal = res.data.total;
          this.tableLoading = false;
        }
      })
      .catch((e) => {
        this.tableLoading = false;
      });
    },
    //多选，数据选择改变
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //编辑/查看回显
    getBackAll(id){
      getBack(id).then((res) => {
        if (res.code === 0) {
          this.form.databaseName =res.data.databaseName;
          this.form.alias =res.data.alias;
          this.form.type = res.data.type;
          this.form.ip = res.data.ip;
          this.form.port = res.data.port;
          this.form.username = res.data.username;
          this.form.password = res.data.password;
          this.form.description =res.data.description;
          this.form.id =res.data.id;
          this.passwordFlag = res.data.password
        }
      })
      .catch((e) => {
        this.tableLoading = false;
      });
    },
    operate(row,status){
      if(status==='新增'){
        this.status = 'add'
        Object.keys(this.form).forEach(key =>{this.form[key] = ''})
        this.showDialog = true;
      }else if(status === '编辑'){
        this.status = 'edit'
        this.getBackAll(row.id)
        this.showDialog = true;
      }else{
        this.status = 'view'
        this.getBackAll(row.id)
        this.viewDialog = true
      }
    },
    //删除
    delList(row) {
      this.$confirm("是否确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          deleteList(row.id).then((res) => {
            if (res.code === 0) {
              this.$message.success("删除成功");
              this.getList();
            }
          })
          .catch((e) => {
            this.tableLoading = false;
          });
      })
      .catch((e) => console.log(e));
    },
    //批量删除
    // multiDelPortal() {
    //   this.$confirm("是否确认删除", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   }).then(() => {
    //     let ids = this.multipleSelection.map((item) => {
    //       return item.id;
    //     });
    //     batchDelPortal(ids).then(res => {
    //       if (res.code === 0) {
    //         this.$message.success('删除成功')
    //         setTimeout(() => {
    //           window.location.reload()
    //         }, 1000)
    //       } else {
    //         this.$message.error('所选数据删除失败！')
    //       }
    //     }).catch(e => console.log('批量删除：', e))
    //   });
    // },
    //搜索
    searchChange() {
      this.page.pageNo = 1;
      this.tableLoading = true;
      this.getList();
    },
    //搜索重置
    resetSearch() {
      this.searchText = "";
      this.searchChange();
    },
    //每页条数更改
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.page.pageNo = 1;
      this.tableLoading = true;
      this.getList();
    },
    //页码更改
    currentChange(current) {
      this.page.pageNo = current;
      this.tableLoading = true;
      this.getList();
    },

    //取消提交
    cancelFields () {
      this.showDialog = false
      this.$refs["basicForm"].clearValidate()
    },
    //确定提交
    submit(){
      this.updateFlag = true
      this.$refs['basicForm'].validate((valid) => {
        if (!valid) {
          this.updateFlag = false
          return;
        }
        if(this.status === 'add'){
          let params = {
            type: this.form.type,
            ip: this.form.ip,
            port: this.form.port,
            username:this.form.username,
            password: encryption(this.form.password),
            databaseName: this.form.databaseName,
            alias:this.form.alias,
            description:this.form.description
          }
          //数据库创建
          createDatabase(params).then((res) => {
            if (res.code === 0) {
              this.$message.success('新增成功')
              this.showDialog = false
              this.getList()
            }
          })
          .finally(() => {
            setTimeout(() => {
              this.updateFlag = false;
            }, 1000)
          });
        }else{
          let pass = this.passwordFlag
          let newpass = this.form.password
          let params = {
            id:this.form.id,
            type: this.form.type,
            ip: this.form.ip,
            port: this.form.port,
            username:this.form.username,
            password:pass===newpass ? this.form.password:  encryption(this.form.password),
            databaseName: this.form.databaseName,
            alias:this.form.alias,
            description:this.form.description
          }
          //数据库创建
          updateDatabase(params).then((res) => {
            if (res.code === 0) {
              this.$message.success('修改成功')
              this.showDialog = false
              this.getList();
            }
          })
          .finally(() => {
            setTimeout(() => {
              this.updateFlag = false;
            }, 2000)
          });
        }
      });
    }
  },
};
</script>
<style lang="scss" scoped>
  .designer {
    .base {
      margin-right: 20%;
      margin-left: 15%;
      margin-top: 5%;

      .el-form-item {
        margin-bottom: 40px;
      }
    }

    .el-input--mini {
      width: 80px;
    }

    .designHeader {
      display: flex;
      justify-content: space-around;
      align-items: center;

      .designStep {
        display: flex;
        justify-content: center;
        width: 100%;
        margin-left: 10%;

        .designStepItem {
          width: 33.3%;
          display: flex;
          align-items: center;
          justify-content: space-around;

          .designStepLine {
            display: inline-block;
            width: calc(100% - 110px);
            height: 2px;
          }

          .designStepIndex {
            font-size: 16px;
            color: white;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            text-align: center;
            line-height: 30px;
            margin-right: 5px;
            margin-left: 5px;
            font-weight: bold;
          }

          .designStepTitle {
            font-size: 14px;
            font-weight: bold;
            width: 70px;
          }
        }
      }
    }
  }

</style>
<style lang="scss">
  .el-descriptions-item__label:not(.is-bordered-label){
    width: 20%;
    text-align: right;
    align-items: center;
    margin: auto 2%;
  }
  .el-descriptions-item__content{
    width: 75%;
  }
  .el-dialog__header{
    border-bottom: 1px solid #eee;
  }
  .el-dialog__title {
    font-size: 15px;
    color: #303133;
    font-weight: bold;
  }
  .el-dialog__body{
    padding-top: 20px;
  }
  .designer {
    .el-table {
      box-sizing: border-box;

      &::before {
        height: 0px;
      }
    }

    .el-table--border::after,
    .el-table--group::after {
      width: 0px;
      height: 0px;
    }

    .tableInfo {
      .el-table__cell {
        // border-bottom: 0px;
        padding: 0px;
      }
    }
  }
</style>
